/**
 * Create by CaoWenjian
 *
 * @copyRight: 2018
 **/
package com.bjboot.caocao.common.exception;

import com.bjboot.caocao.common.config.Constant;
import com.bjboot.caocao.common.utils.HttpServletUtils;
import com.bjboot.caocao.common.utils.Result;
import com.bjboot.caocao.system.domain.LogDO;
import com.bjboot.caocao.system.domain.UserDO;
import com.bjboot.caocao.system.service.LogService;
import com.bjboot.caocao.system.shiro.ShiroUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 *@Description 异常处理器
 *@Author 操文健
 *@Date 2018-09-20 上午8:48
 *@Version 1.0
 **/
@RestControllerAdvice
public class BJExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    LogService logService;

    /**
     * 对没权限的异常进行捕捉
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
        logger.info("权限不足，进入权限不足Handler");
        logger.error(e.getMessage());
        if (HttpServletUtils.jsAjax(request)) {
            return Result.error(Constant.ERROR_CODE_403, Constant.ERROR_CODE_403_NAME);
        }
        return new ModelAndView("error/403");
    }

    @ExceptionHandler({Exception.class})
    public Object handleException(Exception e, HttpServletRequest request) {
        LogDO logDO = new LogDO();
        logDO.setGmtCreate(new Date());
        logDO.setOperation(Constant.LOG_ERROR);
        logDO.setMethod(request.getRequestURL().toString());
        logDO.setParams(e.toString());
        UserDO current = ShiroUtils.getUser();
        if (null != current) {
            logDO.setUserId(current.getUserId());
            logDO.setUsername(current.getUsername());
        }
        logService.save(logDO);
        logger.error(e.getMessage(), e);
        if (HttpServletUtils.jsAjax(request)) {
            return Result.error(Constant.ERROR_CODE_500, Constant.ERROR_CODE_500_NAME);
        }
        return new ModelAndView("error/500");
    }
}
